<?php

namespace app\api\controller;

use app\admin\model\template\Review as TemplateReviewModel;
use app\admin\model\template\Template as TemplateModel;
use app\common\controller\Api;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\ValidateException;

class Template extends Api
{
    // 验证失败是否抛出异常
    protected $failException = true;
    protected $noNeedLogin = [];
    protected $noNeedRight = ["*"];
    private TemplateModel $model;
    private TemplateReviewModel $reviewModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TemplateModel();
        $this->reviewModel = new TemplateReviewModel();
    }


    /**
     * @title 模板上架
     * @param product_name 必选 string 商品名
     * @param name 必选 string 模板名
     * @param thumbnail 必选 string 缩略图
     * @param description 必选 string 产品描述
     * @param price 必选 int 价格
     * @param product_id 必选 int 节点ID
     * @author Trace
     * @method POST
     * @url api/template/reviewTemplate
     */
    public function reviewTemplate()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\template\Template.reviewTemplate');

            $price = $this->request->post('price');
            if ($price < 10) {
                $this->error('价格不能小于10');
            }

            if (strlen($price) > 6) {
                $this->error('请填写6位及以内的整数');
            }

            $product_id = $this->request->post('product_id/d');
//            if ($this->reviewModel->where('product_id', $product_id)->where('status', 0)->find()) {
//                $this->error('模板正在审核中');
//            }
            $user = $this->auth->getUser();
            //包含引用模板无法上架
            if ($this->model->isTemplateNodeByProductId((int)$product_id,$user->id)) {
                $this->error('模板中包含引用模板，无法上架');
            }
            //所有节点数据
            $allNode = $this->model->getTemplateNodeByProductId($product_id);
            $factor_num = array_sum($allNode->column('is_factor'));
            //所有节点详情数据
            $allNodeDetail = $this->model->getTemplateNodeDetailByProductId($product_id);

            //数据量
            $data_num = $allNodeDetail->count();

        } catch (ValidateException  $e) {
            $this->error($e->getMessage());
        }

        $thumbnail = $this->request->post('thumbnail', null, 'trim');
        $images = $this->request->post('images/a') ?: [];
        if (count($images) > 9) {
            $this->error('最多上传9张图片');
        }


        $data = [
            'name' => $this->request->post('name'),
            'category_id' => $this->request->post('category_id/d'),
            'group_id' => $this->request->post('group_id/d'),
            'sn' => $this->model->getTemplateSn(),
            'user_id' => $user->id,
            'company_id' => $user->company_id,
            'product_id' => $product_id,
            'product_name' => $this->request->post('product_name'),
            'description' => $this->request->post('description', '', 'trim'),
            'thumbnail' => $thumbnail ?: 'https://battery001.zthj.net/uploads/20240816/FvZ7vX7S_Zu_MbHPIsV3SRzsoGeH.jpg',
            'images' => $images,
            'snapshot' => $allNode->toArray(),
            'node_detail' => $allNodeDetail->toArray(),
            'price' => $price,
            'data' => $data_num,
            'quote' => $factor_num,
            'node' => $allNode->count(),
        ];
        Db::startTrans();
        try {
            $template = $this->model::create($data);
            unset($data['sn'],$data['company_id']);
            $template->review()->save($data);
            Db::commit();
            $this->success('提交成功', ['template_id' => $template->id]);
        } catch (ValidateException  $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 获取模板审核信息
     * @param template_id 必选 int 数据库ID
     * @author Trace
     * @method Get
     * @url api/template/getTemplateReviewInfo
     */
    public function getTemplateReviewInfo()
    {
        try {
            $this->validate($this->request->get(), 'app\admin\validate\template\Template.getTemplateReviewInfo');
            $template_id = $this->request->get('template_id');
            $factorReview = $this->reviewModel->where('template_id', $template_id)
                ->field('id,name,product_name,category_id,group_id,price,images,thumbnail,description,status,reason,checktime,createtime')
                ->order('createtime', 'desc')
                ->find()?->append(['category_name','group_name']);
            $this->success('请求成功', $factorReview);
        } catch (DataNotFoundException|ModelNotFoundException|DbException|ValidateException $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @title 模板重新编辑
     * @param product_name 必选 string 商品名
     * @param name 必选 string 模板名
     * @param thumbnail 必选 string 缩略图
     * @param description 必选 string 产品描述
     * @param price 必选 int 价格
     * @param template_id 必选 int 数据库ID
     * @author Trace
     * @method Get
     * @url api/template/editTemplateInfo
     */
    public function editTemplateInfo()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        try {
            $this->validate($this->request->post(), 'app\admin\validate\template\Template.editTemplateInfo');
            $template_id = $this->request->post('template_id');
            if ($this->reviewModel->where('template_id', $template_id)->where('status', 0)->find()) {
                $this->error('模板正在审核中');
            }
            $price = $this->request->post('price');
            if ($price < 10) {
                $this->error('价格不能小于10');
            }
            if (strlen($price) > 6) {
                $this->error('请填写6位及以内的整数');
            }
            $template = $this->model->where('id', $template_id)->find();
            $images = $this->request->post('images/a') ?: [];
            if (count($images) > 9) {
                $this->error('最多上传9张图片');
            }
            $reviewData = [
                'user_id' => $template->user_id,
                'product_id' => $template->product_id,
                'name' => $this->request->post('name'),
                'category_id' => $this->request->post('category_id/d'),
                'group_id' => $this->request->post('group_id/d'),
                'price' => $this->request->post('price'),
                'product_name' => $this->request->post('product_name'),
                'description' => $this->request->post('description', '', 'trim'),
                'images' => $images,
                'thumbnail' => $this->request->post('thumbnail', null, 'trim') ?: 'https://battery001.zthj.net/uploads/20240816/FvZ7vX7S_Zu_MbHPIsV3SRzsoGeH.jpg',
            ];
            if (!$template->company_id) {
                $user = $this->auth->getUser();
                $template->company_id = $user->company_id;
            }
            Db::transaction(function () use ($template, $reviewData) {
                $template->check_status = 0;
                $template->save();
                $template->review()->save($reviewData);
            });

            $this->success('提交成功');
        } catch (ValidateException|DbException $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * @title 我的模板库
     * @param search 非必选 string 搜索模板名
     * @author Trace
     * @method Get
     * @url api/template/myTemplateList
     */
    public function myTemplateList()
    {
        try {
            $search = $this->request->get('search');
            $user_id = $this->auth->id ?: 1;
            $limit = $this->request->get('limit', 15);

            $orderTemplateIds = \app\admin\model\template\Order::join('zt_template t', 'zt_order.template_id=t.id')
                ->where('zt_order.type', 1)
                ->where('zt_order.pay_state', 1)
                ->where('zt_order.user_id', $user_id)
                ->where(function ($query) use ($search) {
                    if ($search) {
                        $query->where('t.name', 'like', '%' . $search . '%')
                            ->whereOr('t.sn',$search);
                    }
                })
                ->distinct(true)
                ->column('t.id');

            $selfTemplateIds = $this->model->where('user_id', $user_id)
                ->where('status',1)
                ->where(function ($query) use ($search) {
                    if ($search) {
                        $query->where('name', 'like', '%' . $search . '%')
                            ->whereOr('sn',$search);
                    }
                })->column('id');
            $template_id = array_unique(array_merge($orderTemplateIds, $selfTemplateIds));

            $data = $this->model->whereIn('id', $template_id)
                ->field('id,name,sn,product_name,user_id,data,quote,node,product_id')
                ->order('id', 'desc')
                ->paginate($limit);
            $this->success('请求成功', $data);
        } catch (DbException$e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * @title 我的模板库
     * @param template_id 必选 string 模板ID
     * @author Trace
     * @method Get
     * @url api/template/getTemplateInfo
     */
    public function getTemplateInfo()
    {
        try {
            $template = $this->model->where('id', $this->request->get('template_id'))
                ->field('id,name,sn,product_name,data,quote,node,snapshot')
                ->find();
            if (!$template) {
                $this->error('模板不存在');
            }
            if ($template->snapshot && is_array($template->snapshot)) {
                $template->snapshot = $this->buildTree($template->snapshot);
            } else {
                $template->snapshot = [];
            }
            $this->success('请求成功', $template);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $this->error($e->getMessage());
        }
    }


}
